import React, { useState } from 'react'
import { View, Text, Textarea, Button as TaroButton } from '@tarojs/components'
import { Button, ConfigProvider, Uploader, Toast } from '@nutui/nutui-react-taro'
import Taro from '@tarojs/taro'
import './index.scss'

function Publish() {
  const [content, setContent] = useState('')
  const [imageFiles, setImageFiles] = useState<any[]>([])
  const [videoFile, setVideoFile] = useState<any>(null)
  const [mediaType, setMediaType] = useState<'image' | 'video'>('image')
  const [showToast, setShowToast] = useState(false)
  const [toastMsg, setToastMsg] = useState('')

  const handleContentChange = (e) => {
    setContent(e.target.value)
  }

  const handleMediaTypeChange = (type: 'image' | 'video') => {
    setMediaType(type)
    // 切换媒体类型时清空已选择的文件
    setImageFiles([])
    setVideoFile(null)
  }

  const handleImageUpload = async () => {
    try {
      const res = await Taro.chooseImage({
        count: 9 - imageFiles.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      })
      
      const newFiles = res.tempFilePaths.map(path => ({
        url: path,
        status: 'success',
        message: '上传成功',
        type: 'image'
      }))
      
      setImageFiles([...imageFiles, ...newFiles])
    } catch (error) {
      console.error('选择图片失败', error)
    }
  }

  const handleVideoUpload = async () => {
    try {
      const res = await Taro.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: 'back'
      })
      
      setVideoFile({
        url: res.tempFilePath,
        status: 'success',
        message: '上传成功',
        type: 'video',
        duration: res.duration
      })
    } catch (error) {
      console.error('选择视频失败', error)
    }
  }

  const handleDeleteImage = (file, index) => {
    const newFiles = [...imageFiles]
    newFiles.splice(index, 1)
    setImageFiles(newFiles)
  }

  const handleDeleteVideo = () => {
    setVideoFile(null)
  }

  const handleSubmit = () => {
    if (!content.trim()) {
      setToastMsg('请输入笔记内容')
      setShowToast(true)
      return
    }

    if (mediaType === 'image' && imageFiles.length === 0) {
      setToastMsg('请至少上传一张图片')
      setShowToast(true)
      return
    }

    if (mediaType === 'video' && !videoFile) {
      setToastMsg('请上传一个视频')
      setShowToast(true)
      return
    }

    // 模拟发布成功
    setToastMsg('发布成功！')
    setShowToast(true)
    
    // 清空表单
    setTimeout(() => {
      setContent('')
      setImageFiles([])
      setVideoFile(null)
    }, 1500)
  }

  return (
    <ConfigProvider>
      <View className='publish-page'>
        <View className='publish-header'>
          <Text className='header-title'>发布露营笔记</Text>
        </View>

        <View className='publish-content'>
          <Textarea
            className='content-textarea'
            value={content}
            onInput={handleContentChange}
            placeholder='分享你的露营体验...'
            maxlength={1000}
            autoHeight
          />
          
          <View className='media-type-switcher'>
            <Button 
              type={mediaType === 'image' ? 'primary' : 'default'}
              onClick={() => handleMediaTypeChange('image')}
              size='small'
            >
              图片
            </Button>
            <Button 
              type={mediaType === 'video' ? 'primary' : 'default'}
              onClick={() => handleMediaTypeChange('video')}
              size='small'
            >
              视频
            </Button>
          </View>

          {mediaType === 'image' && (
            <View className='upload-container'>
              <View className='upload-list'>
                {imageFiles.map((file, index) => (
                  <View className='upload-item' key={index}>
                    <View className='upload-image' style={{ backgroundImage: `url(${file.url})` }}>
                      <View className='delete-btn' onClick={() => handleDeleteImage(file, index)}>×</View>
                    </View>
                  </View>
                ))}
                {imageFiles.length < 9 && (
                  <View className='upload-item add-item' onClick={handleImageUpload}>
                    <Text className='add-icon'>+</Text>
                  </View>
                )}
              </View>
            </View>
          )}

          {mediaType === 'video' && (
            <View className='upload-container'>
              {videoFile ? (
                <View className='video-container'>
                  <View className='delete-btn' onClick={handleDeleteVideo}>×</View>
                  <video src={videoFile.url} className='video-preview' controls></video>
                </View>
              ) : (
                <View className='upload-video-btn' onClick={handleVideoUpload}>
                  <Text className='add-icon'>+</Text>
                  <Text className='upload-text'>上传视频</Text>
                </View>
              )}
            </View>
          )}
        </View>

        <View className='publish-footer'>
          <TaroButton className='submit-btn' type='primary' onClick={handleSubmit}>
            发布
          </TaroButton>
        </View>

        <Toast
          visible={showToast}
          content={toastMsg}
          onClose={() => setShowToast(false)}
        />
      </View>
    </ConfigProvider>
  )
}

export default Publish 